/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package ar.com.remiseria.frame;

import ar.com.remiseria.bo.ClienteBO;
import ar.com.remiseria.bo.CuentaCorrienteClienteBO;
import ar.com.remiseria.entities.Cliente;
import ar.com.remiseria.entities.CuentaCorrienteCliente;
import ar.com.remiseria.utils.Constantes;
import ar.com.remiseria.utils.PropertiesReader;
import java.awt.Component;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author cmvalls
 */
public class AltaCuentaCorrienteClienteFrame extends javax.swing.JFrame {
    
    private int paginaActual = 1;
    private int paginasTotales = 1;
    private List<Cliente> listaClientes = new ArrayList<Cliente>();
    

    /**
     * Creates new form NuevaCuentaCorrienteCliente
     */
    public AltaCuentaCorrienteClienteFrame() {
        initComponents();    
        this.getClientes(false);
        this.verificarPaginado();
        this.deshabilitarCampos();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        clientesTable = new javax.swing.JTable();
        pagAnteriorBtn = new javax.swing.JButton();
        paginasLbl = new javax.swing.JLabel();
        pagSiguienteBtn = new javax.swing.JButton();
        crearCuentaBtn = new javax.swing.JButton();
        volverBtn = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        clienteTxt = new javax.swing.JTextField();
        buscarClienteBtn = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        crearCuentaCorrienteMenuBtn = new javax.swing.JMenuItem();
        volverMenuBtn = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        clientesTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(clientesTable);

        pagAnteriorBtn.setText("Ant");

        paginasLbl.setText("Pagina X de Y");

        pagSiguienteBtn.setText("Sig");

        crearCuentaBtn.setText("Crear Cuenta Corriente");
        crearCuentaBtn.setToolTipText("Crea una cuenta corriente para el cliente seleccionado.");
        crearCuentaBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                crearCuentaBtnActionPerformed(evt);
            }
        });

        volverBtn.setText("Volver");
        volverBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                volverBtnActionPerformed(evt);
            }
        });

        jLabel1.setText("Buscar cliente:");

        buscarClienteBtn.setText("Buscar");
        buscarClienteBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buscarClienteBtnActionPerformed(evt);
            }
        });

        jMenu1.setText("Menu");

        crearCuentaCorrienteMenuBtn.setText("Crear cuenta p/ seleccionado");
        crearCuentaCorrienteMenuBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                crearCuentaCorrienteMenuBtnActionPerformed(evt);
            }
        });
        jMenu1.add(crearCuentaCorrienteMenuBtn);

        volverMenuBtn.setText("Volver");
        volverMenuBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                volverMenuBtnActionPerformed(evt);
            }
        });
        jMenu1.add(volverMenuBtn);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Ayuda");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 586, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(pagAnteriorBtn)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(paginasLbl)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(pagSiguienteBtn))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(buscarClienteBtn)
                                    .addComponent(clienteTxt))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(crearCuentaBtn, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(volverBtn, javax.swing.GroupLayout.Alignment.TRAILING))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 247, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(pagAnteriorBtn)
                    .addComponent(paginasLbl)
                    .addComponent(pagSiguienteBtn)
                    .addComponent(crearCuentaBtn))
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(volverBtn)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(clienteTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buscarClienteBtn)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void crearCuentaBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_crearCuentaBtnActionPerformed
        this.crearCuentaCorrienteSeleccionado();
    }//GEN-LAST:event_crearCuentaBtnActionPerformed

    private void buscarClienteBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buscarClienteBtnActionPerformed
        this.buscarClientes();
    }//GEN-LAST:event_buscarClienteBtnActionPerformed

    private void volverBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_volverBtnActionPerformed
        this.irAAdministracionDeCuentaCorrienteCliente();
    }//GEN-LAST:event_volverBtnActionPerformed

    private void crearCuentaCorrienteMenuBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_crearCuentaCorrienteMenuBtnActionPerformed
        this.crearCuentaCorrienteSeleccionado();
    }//GEN-LAST:event_crearCuentaCorrienteMenuBtnActionPerformed

    private void volverMenuBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_volverMenuBtnActionPerformed
        this.irAAdministracionDeCuentaCorrienteCliente();
    }//GEN-LAST:event_volverMenuBtnActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AltaCuentaCorrienteClienteFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AltaCuentaCorrienteClienteFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AltaCuentaCorrienteClienteFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AltaCuentaCorrienteClienteFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AltaCuentaCorrienteClienteFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buscarClienteBtn;
    private javax.swing.JTextField clienteTxt;
    private javax.swing.JTable clientesTable;
    private javax.swing.JButton crearCuentaBtn;
    private javax.swing.JMenuItem crearCuentaCorrienteMenuBtn;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton pagAnteriorBtn;
    private javax.swing.JButton pagSiguienteBtn;
    private javax.swing.JLabel paginasLbl;
    private javax.swing.JButton volverBtn;
    private javax.swing.JMenuItem volverMenuBtn;
    // End of variables declaration//GEN-END:variables

    private void getClientes(boolean tieneFiltro) {
         ClienteBO clienteBO = new ClienteBO();
        
        DefaultTableModel modelo = new DefaultTableModel();
        modelo.addColumn("Telefono");
        modelo.addColumn("Codigo Cliente");
        modelo.addColumn("Nombre");
        modelo.addColumn("Apellido");        
        modelo.addColumn("Documento");
        modelo.addColumn("Domicilio");
        
        try{
            if(!tieneFiltro){
                listaClientes = clienteBO.getAllClientes(paginaActual);
            }
        }catch(Exception ex){
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
        
        if(listaClientes != null && !listaClientes.isEmpty()){
            for(Cliente cliente : listaClientes){
                Object[] clientes = new Object[6];
                clientes[0] = cliente.getTelefono();
                clientes[1] = cliente.getCodigo();
                clientes[2] = cliente.getNombre();
                clientes[3] = cliente.getApellido();
                
                clientes[4] = cliente.getDocumento().getTipoDeDocumento().getDescripcion()+
                                " - "+ cliente.getDocumento().getNumero();
                
                String domicilioFormateado = cliente.getDomicilio().getCalle();
                if(cliente.getDomicilio().getNumero() != null){
                    domicilioFormateado+=" "+cliente.getDomicilio().getNumero();
                }
                if(cliente.getDomicilio().getPiso() != null){
                    domicilioFormateado+=" Piso "+cliente.getDomicilio().getPiso();
                }
                if(cliente.getDomicilio().getDepartamento() != null){
                    domicilioFormateado+=" Dpto "+cliente.getDomicilio().getDepartamento();
                }
                if(cliente.getDomicilio().getCodigoPostal() != null){
                    domicilioFormateado+=",C.P "+cliente.getDomicilio().getCodigoPostal();
                }
                if(cliente.getDomicilio().getLocalidad() != null){
                    domicilioFormateado+= " - "+cliente.getDomicilio().getLocalidad();
                }
                if(cliente.getDomicilio().getProvincia() != null){
                    domicilioFormateado+=", "+cliente.getDomicilio().getProvincia();
                }
                
                clientes[5] = domicilioFormateado;
                                
                modelo.addRow(clientes);
            }
            
        }
        clientesTable.setModel(modelo);
    }

    private void verificarPaginado() {
        ClienteBO clienteBO = new ClienteBO();
        int clientesTotales = 0;
        
        try{
            clientesTotales = clienteBO.getChoferesCount(); 
        }catch(Exception ex){
            ex.printStackTrace();
        }
        
        if(clientesTotales != 0){
            int cantidadPaginas = clientesTotales % Constantes.PAG_MAX_RESULTS;
            if(cantidadPaginas == 0){
                cantidadPaginas = clientesTotales / Constantes.PAG_MAX_RESULTS;
            }else{
                cantidadPaginas = (clientesTotales / Constantes.PAG_MAX_RESULTS) + 1;
            }
            paginasTotales = cantidadPaginas;
        }
        
        paginasLbl.setText("Pagina "+paginaActual+" de "+paginasTotales);
        
        if(paginaActual == 1){
            pagAnteriorBtn.setEnabled(false);
        }else{
            pagAnteriorBtn.setEnabled(true);
        }
        
        if(paginaActual == paginasTotales){
            pagSiguienteBtn.setEnabled(false);
        }else{
            pagSiguienteBtn.setEnabled(true);
        }
    }

    private void crearCuentaCorrienteSeleccionado() {
        int index = clientesTable.getSelectedRow();
        
        Cliente cliente = listaClientes.get(index);
        
        CuentaCorrienteCliente cuentaCorrienteCliente = new CuentaCorrienteCliente();
        cuentaCorrienteCliente.setCliente(cliente);
        
        CuentaCorrienteClienteBO cuentaCorrienteClienteBO = new CuentaCorrienteClienteBO();
        try{
            cuentaCorrienteCliente = cuentaCorrienteClienteBO.saveNewCuentaCorrienteCliente(cuentaCorrienteCliente);
            JOptionPane.showMessageDialog(this, 
                    PropertiesReader.getInstance().getApplicationMessage("info.alta.cuentacorrientecliente.guardadook"));
            this.deshabilitarCampos();
        }catch(Exception ex){
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, ex);
        }
        
    }

    private void deshabilitarCampos() {
       // TODO: Agregar todas las deshabilitaciones pertinentes al terminar de modelar el jFrame.
    }

    private void buscarClientes() {
        ClienteBO clienteBO = new ClienteBO();
        String palabraClave = clienteTxt.getText();
        if(palabraClave.trim().length() > 0){
            try{
                listaClientes = clienteBO.getAllClientesByFiltro(paginaActual, palabraClave);
                this.getClientes(true);
            }catch(Exception ex){
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this, ex);
            }
        }
    }

    private void irAAdministracionDeCuentaCorrienteCliente() {
        AdministracionDeCuentaCorrienteClienteFrame adccc = new AdministracionDeCuentaCorrienteClienteFrame();
        adccc.setVisible(true);
        this.dispose();
    }
}
